<script setup lang="ts">
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch } from 'vue'
import { ProductData } from '@/api/product/types'
import { useI18n } from '@/hooks/web/useI18n'
import { useValidator } from '@/hooks/web/useValidator'
import { FormSchema } from '@/types/form'

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<ProductData>>,
    default: () => null
  }
})

const { t } = useI18n()

const schema = reactive<FormSchema[]>([
  {
    field: 'productCode',
    label: '商品编号',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'productName',
    label: '商品名称',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'currentpriceProduct',
    label: '商品售价',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'createDate',
    label: '上传时间',
    component: 'DatePicker',
    componentProps: {
      type: 'Date',
      valueFormat: 'YYYY-MM-DD'
    },
  },
  {
    field: 'createUser',
    label: '上传人',
    component: 'Input',
  },

  {
    field: 'productSate',
    label: '审核状态',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '审核中',
          value: 2
        },
        {
          label: '审核通过',
          value: 3
        },
        {
          label: '审核不通过',
          value: 4
        }
      ]
    }
  },
  {
    field: 'productLabel',
    label: '商品标签',
    component: 'Input'
  },
  {
    field: 'searchKeywords',
    label: '关键字',
    component: 'Input'
  },
  {
    field: 'fabulous',
    label: '点击量',
    component: 'Input',
  },
  {
    field: 'collectionVolume',
    label: '收藏量',
    component: 'Input',
  },
  {
    field: 'productSales',
    label: '销量',
    component: 'Input',
  },
  {
    field: 'productDescription',
    label: '商品简介',
    component: 'Input',
    componentProps: {
      type: 'textarea',
      rows: 1
    }
  }
])

const rules = reactive({
  productCode: [required()],
  productName: [required()],
  currentpriceProduct: [required()],
  createDate: [required()],
  trueName: [required()],
  categroyName: [required()],
  productSate: [required()],
  productLabel: [required()],
  searchKeywords: [required()],
  productDescription: [required()]
})

const { register, methods, elFormRef } = useForm({
  schema
})

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    const { setValues, setSchema } = methods
    setValues(currentRow)
    setSchema([
      {
        field: 'remark',
        path: 'componentProps.defaultHtml',
        value: currentRow
      }
    ])
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  elFormRef,
  getFormData: methods.getFormData
})
</script>

<template>
  <Form :rules="rules" @register="register" />
</template>
